﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using jnxceq.Common.Log;
using jnxceq.Model;

namespace jnxceq.Common.Net
{
    public class ControlConnection
    {
        Thread threadReceive;        
        Form1 formMain;
        /// <summary>
        /// 接收数据的临时缓冲区
        /// </summary>
        byte[] bytesTemp = new byte[1024];
        /// <summary>
        /// 临时缓冲区的实际数据长度
        /// </summary>
        int intPacketLength = 0;


        public ControlConnection()
        {
            //socketClient = socketClient;
            //this.formMain = form;
        }
        #region 开启线程
        /// <summary>
        /// 开始 连接管理 开启新的线程
        /// </summary>
        public void start(object o)
        {
            Socket client = o as Socket;
            try
            {            

                //创建线程
                threadReceive = new Thread(receive);
                //开始线程
                threadReceive.IsBackground = true;
                threadReceive.Start(client);
            }
            catch (Exception e)
            {
                Console.WriteLine("main: 异常 " + e.Message.ToString() + e.ToString());
            }
        }
        #endregion
        #region 处理数据方法
        /// <summary>
        /// 开始接收数据，处理
        /// </summary>
        private void receive(object o)
        {
            Socket client = o as Socket;
            try
            {
                //接收数据缓冲区
                byte[] bytesReceive = new byte[1024];
                //读取到的数据的个数
                int RcvBytes = 0;


                //循环接收数据
                while (true)
                {
                    //接收数据
                    RcvBytes = client.Receive(bytesReceive);

                    string strReceive = Tools.ToHex(bytesReceive, RcvBytes);

                    #region

                    if (RcvBytes > 0)
                    {
                        int result = CheckData(strReceive);
                        if (result == 1)
                        {
                            string id = GetID(strReceive);
                            string type = GetType(strReceive);
                            string interval = GetInter(strReceive);
                            Form1.DdisEqu(type + "&" + id + "&" + client.RemoteEndPoint.ToString() + "&" + interval);
                            showData(id, type, strReceive);
                            string ins = "";
                            if (Form1.dict.ContainsKey(id) == true)
                            {
                                ins = Form1.dict[id];
                            }
                            Thread.Sleep(2000);
                            client.Send(Tools.HexToByte(GetSend(strReceive, ins)));
                            //client.Close();
                            //return;
                        }
                        else
                        {
                            Form1.DdisData("接收到数据异常： " + strReceive);
                        }
                    }
                    else
                    {
                        client.Close();
                        return;

                    }
                    #endregion
                }
            }
            catch (Exception e)
            {
                if (e.Message.ToString().Contains("远程主机强迫关闭了一个现有的连接"))
                {
                    client.Close();
                    return;
                }
                //WFLog.Write("main: 异常 " + e.Message.ToString() + e.ToString());
                Form1.DdisData("main: 异常 " + e.Message.ToString() + e.ToString());
                Connetion con = new Connetion();
                con.Start();

            }
        }
        public void showData(string id, string type, string strReceive)
        {
            string cn = "";
            if (type == "CB")
            {
                cn = "测报灯";
                char[] num = GetCBNum(strReceive);
                string numstr = "";
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < num.Length; i++)
                {
                    sb.Append(num[i]);
                    sb.Append(',');
                }
                numstr = sb.ToString().Substring(0, sb.Length - 1);
                Form1.DdisData("收到:" + cn + id + "，上传数据" + numstr + "：" + System.DateTime.Now);
                InDatacbd(id, num);
            }

            else if (type == "BB")
            {
                cn = "靶标害虫";
                int[] num = GetNum(strReceive);
                string numstr = "";
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < num.Length; i++)
                {
                    sb.Append(num[i]);
                    sb.Append(',');
                }
                numstr = sb.ToString().Substring(0, sb.Length - 1);
                Form1.DdisData("收到:" + cn + id + "，上传数据" + numstr + "：" + System.DateTime.Now);
                InDataybq(id, num);
            }
            else if (type == "QH")
                cn = "小气候";
            else if (type == "BZ")
                cn = "孢子捕捉";
            else if (type == "SC")
                cn = "杀虫灯";

        }
        public string GetTypeCN(string type)
        {
            //            测报灯：  CB
            //靶标害虫：BB
            //小气候：  QH
            //孢子捕捉：BZ
            //杀虫灯：  SC

            string cn = "";
            if (type == "CB")
                cn = "测报灯";
            else if (type == "BB")
                cn = "靶标害虫";
            else if (type == "QH")
                cn = "小气候";
            else if (type == "BZ")
                cn = "孢子捕捉";
            else if (type == "SC")
                cn = "杀虫灯";
            return cn;
        }
        #region 解析数据
        public void InDatacbd(string id, char[] nums1)
        {
            int idnum = 0;
            int.TryParse(id, out idnum);
            if (idnum != 0)
            {
                Model.t_cbdStatus m = new t_cbdStatus();
                m.sta_ch0 = nums1[7].ToString();
                m.sta_ch1 = nums1[6].ToString();
                m.sta_ch2 = nums1[5].ToString();
                m.sta_ch3 = nums1[4].ToString();
                m.sta_ch4 = nums1[3].ToString();
                m.sta_ch5 = nums1[2].ToString();
                m.sta_ch6 = nums1[1].ToString();
                m.sta_ch7 = nums1[0].ToString();
                m.devID = idnum;
                m.updateTime = DateTime.Now;
                BLL.t_cbdStatus bll = new BLL.t_cbdStatus();
                bll.Add(m);
                Form1.DdisData("测报设备" + id + "数据写入数据库");
            }
            else
            {
                Form1.DdisData("错误写入数据库:" + id + "不能转化为数值！");

            }

        }
        /// <summary>
        /// 得到数据
        /// </summary>
        /// <param name="RcvBytes"></param>
        /// <returns></returns>
        public void InDataybq(string id, int[] nums1)
        {
            int idnum = 0;
            int.TryParse(id, out idnum);
            if (idnum != 0)
            {
                Model.t_ybqstatus m = new t_ybqstatus();
                m.ch0 = nums1[0];
                m.ch1 = nums1[1];
                m.ch2 = nums1[2];
                m.ch3 = nums1[3];
                m.devID = idnum;
                m.updateTime = DateTime.Now;
                BLL.t_ybqstatus bll = new BLL.t_ybqstatus();
                bll.Add(m);
                Form1.DdisData("靶标设备" + id + "数据写入数据库");
            }
            else
            {
                Form1.DdisData("错误写入数据库:" + id + "不能转化为数值！");

            }

        }

        /// <summary>
        /// 检测数据
        /// </summary>
        /// <param name="RcvBytes"></param>
        /// <returns>0、无效包，1、心跳包，2、数据包</returns>
        public int CheckData(string RcvBytes)
        {
            int result = 0;

            if (!string.IsNullOrEmpty(RcvBytes))
            {
                int lenth = -1;//数据长度

                if (RcvBytes.Length == 112 && RcvBytes.Substring(0, 4) == "AA55")//开头
                {
                    //string len1 = RcvBytes.Substring(4, 4);//长度

                    if (RcvBytes.EndsWith("0D0A"))//结尾
                    {
                        result = 1;
                    }
                }
            }
            return result;
        }
        public string GetID(string RcvBytes)
        {
            string id = "";
            for (int i = 0; i < 8; i++)
                id += Tools.HexStringToString(RcvBytes.Substring(12 + i * 2, 2), Encoding.ASCII);
            return id;
        }
        public string GetType(string RcvBytes)
        {
            string id = "";
            for (int i = 0; i < 2; i++)
                id += Tools.HexStringToString(RcvBytes.Substring(8 + i * 2, 2), Encoding.ASCII);
            return id;
        }
        public int[] GetNum(string RcvBytes)
        {
            int[] num = new int[8];
            for (int i = 0; i < 8; i++)
                num[i] = Convert.ToInt32(RcvBytes.Substring(30 + 4 * i, 4), 16);
            return num;
        }
        public char[] GetCBNum(string RcvBytes)
        {
            string a;
            a = Convert.ToString(Convert.ToInt32(RcvBytes.Substring(62, 2), 16), 2);
            for (int i = a.Length; i < 8; i++)
                a = "0" + a;

            return a.ToCharArray();
        }
        public string GetSend(string R, string ins)
        {
            string s = "";
            if (ins != "")
                s = "55AA1701" + R.Substring(8, 20) + ins + "0000000000000D0A";
            else
                s = "55AA1701" + R.Substring(8, 22) + "0000000000000D0A";
            return s;
        }
        //public int[] GetSend(string R, string ins)
        //{
        //    int[] snum = new int[23] { 0x55, 0xAA, 0x17, 0x01, 0x43, 0x42, 0x31, 0x36, 0x30, 0x34, 0x30, 0x30, 0x30, 0x31, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0A };
        //    string s = "";
        //    for (int i = 0; i < 10; i++)
        //    {
        //        snum[4 + i] = Convert.ToInt32("0x" + R.Substring(8 + 2 * i, 2), 16);
        //    }
        //    if (ins != "")
        //    {
        //        snum[14] = Convert.ToInt32("0x" + ins);
        //    }
        //    else
        //    {
        //        snum[14] = Convert.ToInt32("0x" + R.Substring(28, 2), 16);

        //        //s = "55AA1701" + R.Substring(8, 22) + "0000000000000D0A";
        //    }
        //    return snum;
        //}
        public string GetInter(string R)
        {
            //            0x00：10分钟
            //0x01：30分钟
            //0x02：1小时
            //0x03：2小时
            //0x04：4小时
            //0x05：6小时
            //0x06：12小时
            //0x07：24小时
            string r = "";
            string s = R.Substring(28, 2);
            if (s == "00")
                r = "10分钟";
            else if (s == "01")
                r = "30分钟";
            else if (s == "02")
                r = "1小时";
            else if (s == "03")
                r = "2小时";
            else if (s == "04")
                r = "4小时";
            else if (s == "05")
                r = "6小时";
            else if (s == "06")
                r = "12小时";
            else if (s == "07")
                r = "24小时";
            return r;
        }

        #endregion
        #endregion
    }
}
